//
//  MBAInfo.swift
//  chat
//
//  Created by 1 on 2023/3/28.
//

import Foundation
import KeychainAccess
import UIKit
import StoreKit
import DeviceKit


struct MBAInfo{

    
    //"FastGPT-APP/2.2.0(iPhone 14 Pro;iOS 16.4;Build/19;Device/07242868-5517-48E7-8CEF-B1E44E135413;SystemType/mobile;)"
    static func getUserAgent() -> String{
        let infoDic = Bundle.main.infoDictionary!
        let app_Build = infoDic["CFBundleVersion"] as! String
        let app_Version = infoDic["CFBundleShortVersionString"] as! String
        
        let model = Device.current.realDevice.description
        let systemName = UIDevice.current.systemName
        let systemVertion = UIDevice.current.systemVersion
        let iphoneInfo = model+";"+systemName+" "+systemVertion
        
        let systemType = Device.current.isPad ? "mpad" : "mobile"
        var userAgent = ""
        if(MBAInfo.isVestP()){
            userAgent = "FastGPT-APP/"+app_Version+"("+iphoneInfo+";Build/"+app_Build+";Device/"+getKeychainIDFV()+";SystemType/"+systemType+";Package/FastAI;)"
        }else{
            userAgent = "FastGPT-APP/"+app_Version+"("+iphoneInfo+";Build/"+app_Build+";Device/"+getKeychainIDFV()+";SystemType/"+systemType+";)"
        }
        print(userAgent)
        return userAgent
    }
    
    static func getBuild() -> String{
        let infoDic = Bundle.main.infoDictionary!
        let app_Build = infoDic["CFBundleVersion"] as! String
        return app_Build
    }
    static func getVersion() -> String{
        let infoDic = Bundle.main.infoDictionary!
        let app_Version = infoDic["CFBundleShortVersionString"] as! String
        return app_Version
    }
    
    
    static func getInfoPackageName() -> String{
//        var packageName = "FastGPT"
//        if(MBAInfo.isVestP()){
//            packageName = "FastAI"
//        }
        let packageName = "FastAI"
        return packageName
    }
    
    static func getInfoPackageID() -> String{
        var packageId = "6447152629"
        if(MBAInfo.isVestP()){
            packageId = "6450734781"
        }
        return packageId
    }
    
    
    fileprivate static var keychainIDFVStatic = ""
    //唯一标识优化：优先拿本地唯一值（二重保护保证不出现用户丢失问题）
    static func getKeychainIDFV() -> String{
        if keychainIDFVStatic.isEmpty{
            var uuid:String = ""
            //fastgpt
            var KEYCHAIN_SERVICE:String = "www.chaodanfan.ai"
            var IMEI_KEY:String = "www.chaodanfan.ai.key"
            if(MBAInfo.isVestP()){
                KEYCHAIN_SERVICE = "www.zhinengpai.fastai"
                IMEI_KEY = "www.zhinengpai.fastai.key"
            }
            
            let keychain = Keychain(service: KEYCHAIN_SERVICE)
            do {
                uuid = try keychain.get(IMEI_KEY) ?? ""
            }catch let error {
                print(error)
            }
            
            if uuid.isEmpty {
                uuid = UUID().uuidString
            }
            
            if let keychainIDFVUserDefaults = UserDefaults.standard.string(forKey: "keychainIDFV"),!keychainIDFVUserDefaults.isEmpty{
                uuid = keychainIDFVUserDefaults
            }
            do {
                try keychain.set(uuid, key: IMEI_KEY)
            }
            catch let error {
                print(error)
                uuid = ""
            }
            UserDefaults.standard.setValue(uuid, forKey: "keychainIDFV")
            keychainIDFVStatic = uuid
        }
        return keychainIDFVStatic
    }
    
    static func openAppStore() {
        guard let url = URL(string: "itms-apps://itunes.apple.com/app/id"+getInfoPackageID()) else { return }
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
    }
    
    static func shareApp(){
        //分享的App URL
        let url = URL(string: "https://apps.apple.com/us/app/id"+getInfoPackageID())!
        //分享的内容
        let shareItems = [getInfoPackageName()+"-智能AI助手聊天机器人", url] as [Any]
        MBAInfo.share(shareItems: shareItems)
    }
    
    static func share(shareItems:[Any]){
        //分享的内容
        let shareItems = shareItems
        //创建分享的ViewController
        let activityViewController = UIActivityViewController(activityItems: shareItems, applicationActivities: nil)
        //获取当前场景的窗口并在其上呈现分享的视图控制器
        if let windowScene = UIApplication.shared.connectedScenes.first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene {
            //在iPad中，必须指定popover的位置
            if let popoverController = activityViewController.popoverPresentationController {
                if let view = windowScene.windows.first?.rootViewController?.view{
                    popoverController.sourceView = view
                    popoverController.sourceRect = CGRect(x: view.bounds.midX, y: view.bounds.midY, width: 0, height: 0)
                    popoverController.permittedArrowDirections = []
                }
            }
            windowScene.windows.first?.rootViewController?.present(activityViewController, animated: true, completion: nil)
            
           }
    }
    
    //加了ai逻辑
    static func requestAIReview(){
        var requestReviewedInt = UserDefaults.standard.integer(forKey: "requestReviewedInt")
        if(requestReviewedInt>2){
            return
        }
        requestReviewedInt+=1
        if(2 == requestReviewedInt){
            MBAInfo.requestReview()
        }
        UserDefaults.standard.set(requestReviewedInt, forKey: "requestReviewedInt")
//        if(UserDefaults.standard.bool(forKey: "requestReviewed")){
//
//        }else{
//            UserDefaults.standard.set(true, forKey: "requestReviewed")
//            MBAInfo.requestReview()
//        }
    }
    
    static func requestReview(){
        if let windowScene = UIApplication.shared.connectedScenes.first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene {
               SKStoreReviewController.requestReview(in: windowScene)
           }
    }
    
    static func windowScene() -> UIWindowScene?{
        return UIApplication.shared.connectedScenes.first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene
    }
    
    static func rootViewController() -> UIViewController?{
        if let windowScene = windowScene(){
            return windowScene.windows.first?.rootViewController
        }else{
            return nil
        }
    }
    
    //是否马甲包
    static func isVestP()->Bool{
        #if VestP
            return true
        #endif
        
        return false
    }
}
